﻿using System;
using System.Windows;
using Microsoft.Windows.Controls;
using StockholmsStad.Runtime.Serialization.DataContract;
using StockholmsStad.Runtime.Serialization.DataContract.Enums;
using StockholmsStad.Windows.UI.Modules.Couple.Interfaces;
using StockholmsStad.Windows.UI.Modules.Couple.Models;
using System.Collections.Generic;
using StockholmsStad.Utilities;
using System.Windows.Input;

namespace StockholmsStad.Windows.UI.Modules.Couple.Controls
{
    /// <summary>
    /// Interaction logic for MonthCalendarControl.xaml
    /// </summary>
    public partial class IndividualBookingControl : IIndividualBookingView
    {
        private readonly IBookingService bookingService;
        private BookingPresentationModel model;
        private List<Minister> ministers;

        public IndividualBookingControl(IBookingService service)
        {
            bookingService = service;
            Initialized += IndividualBookingControl_Initialized;
            InitializeComponent();
            Loaded += IndividualBookingControl_Loaded;

            calendarControl.IsTodayHighlighted = true;
            DataContextChanged += IndividualBookingControl_DataContextChanged;

            calendarControl.SelectedDatesChanged += calendarControl_SelectedDatesChanged;
            cbMinisters.SelectionChanged += cbMinisters_SelectionChanged;
        }

        private void IndividualBookingControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsLoaded && Model != null)
            {
                Model.IsInChangeMode = false;
            }
        }

        #region IIndividualBookingView Members

        public BookingPresentationModel Model
        {
            get { return DataContext as BookingPresentationModel; }
            set
            {
                var booking = value;
                DataContext = booking;

                if (booking.BookedDate != null && !calendarControl.SelectedDate.HasValue)
                    calendarControl.SelectedDate = booking.BookedDate.StartDateTime;
            }
        }

        #endregion

        private void IndividualBookingControl_Initialized(object sender, EventArgs e)
        {
            if(IsLoaded || ministers == null)
            {
                ministers = bookingService.GetMinisters();
                cbMinisters.ItemsSource = ministers;                
            }
        }

        private void cbMinisters_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if(model != null && cbMinisters.SelectedItem != null)
            {
                var minister = (Minister)cbMinisters.SelectedItem;
                model.MinisterCode = minister.MinisterCode;
            }
        }

        private void calendarControl_SelectedDatesChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if(IsLoaded && e.AddedItems != null && e.AddedItems[0] != null)
            {
                bool isEnabled = false;

                if(model == null)
                    return;

                var selected = (DateTime)e.AddedItems[0];

                if(model.BookedDate != null)
                {
                    if (selected.Date.CompareTo(model.BookedDate.StartDateTime.Date) != 0)
                    {
                        model.BookedDate.StartDateTime = selected;
                        isEnabled = true;
                    }
                }
                else
                {
                    model.BookedDate = new TimeBlock {StartDateTime = selected};
                    isEnabled = true;
                }

                //UndoButton.IsEnabled = SaveButton.IsEnabled = isEnabled;
                SaveButton.IsEnabled = isEnabled;
                CancelButton.IsEnabled = !isEnabled;
            }
        }

        private void IndividualBookingControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            model = DataContext as BookingPresentationModel;

            if (model == null)
                return;

            if (string.IsNullOrEmpty(model.MinisterCode))
                cbMinisters.SelectedItem = null;
            else
                cbMinisters.SelectedIndex = SetSelectedIndex(model.MinisterCode);

            SetSelectedDate();
            CancelButton.IsEnabled = model.BookedDate != null;
        }

        private void SetSelectedDate()
        {
            if(model != null)
            {
                if (model.BookedDate != null)
                {
                    calendarControl.DisplayDate = model.BookedDate.StartDateTime;
                    calendarControl.SelectedDate = model.BookedDate.StartDateTime;
                    SetBlackoutDates(model.BookedDate.StartDateTime);

                    if(string.IsNullOrEmpty(TextBoxDate.Text))
                    {
                        TextBoxDate.Text = model.BookedDate.StartDateTime.ToString("yyyy-MM-dd");
                    }
                }
                else
                {
                    TextBoxDate.Text = string.Empty;
                }
            }
        }

        private void ChangeButton_Click(object sender, RoutedEventArgs e)
        {
        }
        
        //private void UndoButton_Click(object sender, RoutedEventArgs e)
        //{
        //    UndoButton.IsEnabled = false;
        //    SaveButton.IsEnabled = false;

        //    Model = bookingService.GetBooking(model.TicketId.Value);
        //}

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            Mouse.OverrideCursor = Cursors.Wait;

            CancelButton.IsEnabled = false;
            SaveButton.IsEnabled = false;

            // Reset controls
            TextBoxDate.Text = string.Empty;
            cbMinisters.SelectedItem = null;
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if(cbMinisters.SelectedItem == null)
            {
                MessageBox.Show("Du måste ange en förrättare. Välj i listan ovan. ",
                                "Information", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            Mouse.OverrideCursor = Cursors.Wait;

            model.SaveCommand.Execute(model);
            CancelButton.IsEnabled = true;
            SaveButton.IsEnabled = true;
        }

        private int SetSelectedIndex(string ministerCode)
        {
            for(int i = 0; i < cbMinisters.Items.Count; i++)
            {
                var minister = (Minister)cbMinisters.Items[i];

                if(minister != null && minister.MinisterCode.Equals(ministerCode))
                    return i;
            }

            return -1;
        }

        // Återigen en bugg i datumkontrollen. Om bokningsdatum ligger bakåt i tiden,
        // kan inte den "blackas ut" får då kan inte selected date sättas (vilket vi
        // vill kunna göra). Denna kod återfinns i ordinarybookingcontrol.xaml.cs, så
        // ändringar i denna kräver ändringar även i ordinarybooking
        private void SetBlackoutDates(DateTime bookedDate)
        {
            // rensa tidigare blackout-dagar
            calendarControl.BlackoutDates.Clear();
            if (bookedDate.CompareTo(DateTime.Now) <= 0)
            {
                calendarControl.BlackoutDates.Add(new CalendarDateRange
                {
                    Start = DateTime.MinValue,
                    End = bookedDate.Date.AddDays(-1)
                });
                calendarControl.BlackoutDates.Add(new CalendarDateRange
                {
                    Start = bookedDate.Date.AddDays(1),
                    End = DateTime.Now
                });
            }
            else
            {
                calendarControl.BlackoutDates.AddDatesInPast();
            }
        }

    }
}